package com.hxzy.util;

import com.hxzy.config.MinioConfig;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @Author wy
 * @Description TODO
 * @Date 2023/8/27 11:16
 * @Version 1.0
 */
@Component
public class MinioUtil {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConfig minioConfig;


    /**
     * 创建存储桶
     * @param bucketName
     * @throws Exception
     */
    public void createBucket(String bucketName) throws Exception{
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 上传文件
     * @param bucketName
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadFile(String bucketName, MultipartFile file) throws Exception {

        InputStream fileInputStream=file.getInputStream();
        String filename = "images/"+ UUID.randomUUID().toString()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(filename)
                .stream(fileInputStream, fileInputStream.available(), -1)
                .contentType(file.getContentType())
                .build());
        fileInputStream.close();
        return minioConfig.getEndpoint() + "/" + bucketName + "/" + filename;
    }

    /**
     * 下载文件
     * @param bucketName
     * @param filename
     * @return
     * @throws Exception
     */
    public InputStream downloadFile(String bucketName, String filename) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(filename)
                .build());
    }
}
